﻿using System.ComponentModel;
using System.Linq;
using Newtonsoft.Json;

namespace OneWorks.Extension
{
    public static class ObjectExtensions
    {
        public static string ToJson(this object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        /// <summary>
        /// 获取枚举描述信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToDescriptionByEnum(this object value)
        {
            var attr = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
            return (attr != null) ? attr.Description : value.ToString();
        }

        /// <summary>
        /// 获取类型描述标签内容
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToDescription(this object value)
        {
            var attr = value.GetType().GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
            return (attr != null) ? attr.Description : value.ToString();
        }

    }
}
